home *** CD-ROM | disk | FTP | other *** search
/ The Programmer Disk / The Programmer Disk (Microforum).iso / xpro / c3 / pro14 / stack1.c < prev    next >
Encoding:
C/C++ Source or Header  |  1991-09-07  |  1.2 KB  |  54 lines

  1. /****************************************************************
  2. *    STACK.C - simple demonstration of a stack                    *
  3. *                                                                *
  4. *    To compile: "tcc stack1"                                    *
  5. ****************************************************************/
  6.  
  7. #include <stdio.h>
  8.  
  9. /*------- Declare the stack variables --------*/
  10. #define MAX_STACK 10
  11. int stkArray[MAX_STACK];
  12. int stkIndex = -1;
  13.  
  14. /*----- Push the data item on the stack ------*/
  15. void push(int data)
  16.     {
  17.     /* Does the stack have any room in it? */
  18.     if (stkIndex == MAX_STACK-1)
  19.         {
  20.         fputs("ERROR: stack overflow\n",stderr);
  21.         return;
  22.         }
  23.  
  24.     /* Put the data in the stack */
  25.     stkArray[++stkIndex] = data;
  26.     }
  27.  
  28. /*----- Pop the data item from the stack -----*/
  29. int pop(void)
  30.     {
  31.     /* Does the stack have anything in it? */
  32.     if (stkIndex < 0)
  33.         {
  34.         fputs("ERROR: stack underflow\n",stderr);
  35.         return -1;
  36.         }
  37.  
  38.     /* Get the data off the stack */
  39.     return stkArray[stkIndex--];
  40.     }
  41.  
  42. /*--------- Test the stack functions ---------*/
  43. void main(void)
  44.     {
  45.     int i;
  46.  
  47.     for (i=0; i<11; i++)
  48.         push(i*3);
  49.  
  50.     for (i=9; i>-2; i--)
  51.         if (i*3 != pop())
  52.             fputs("ERROR: bad stack\n",stderr);
  53.     }
  54.